<template>
  <div class="promotion-container">
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-input
        v-model="searchText"
        placeholder="请输入生鲜名称搜索"
        style="width: 300px"
        clearable
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增促销
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="freshFoodName" label="生鲜名称" min-width="120" align="center" />
      <el-table-column prop="originalPrice" label="原价" width="100" align="center">
        <template #default="scope">
          ¥{{ scope.row.originalPrice?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="促销价" width="100" align="center">
        <template #default="scope">
          ¥{{ scope.row.price?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="180" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
            {{ scope.row.status === '1' ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-popconfirm
            title="确定删除该促销吗？"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" link>
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增促销' : '编辑促销'"
      width="500px"
      @close="resetForm">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px">
        <el-form-item label="生鲜" prop="freshFoodId">
          <el-select 
            v-model="formData.freshFoodId" 
            placeholder="请选择生鲜"
            style="width: 100%"
            :disabled="dialogType === 'edit'"
            @change="handleFreshChange">
            <el-option 
              v-for="item in freshOptions" 
              :key="item.id" 
              :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="原价" v-if="formData.originalPrice">
          <el-input :value="'¥' + formData.originalPrice?.toFixed(2)" disabled />
        </el-form-item>
        <el-form-item label="促销价" prop="price">
          <el-input-number 
            v-model="formData.price" 
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledStartDate"
            :default-time="new Date(2000, 0, 1, 0, 0, 0)" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="(time) => disabledEndDate(time)"
            :default-time="new Date(2000, 0, 1, 23, 59, 59)" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="formData.status" label="1">启用</el-radio>
          <el-radio v-model="formData.status" label="2">停用</el-radio>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { get, post } from '@/api/api'

// 数据列表
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchText = ref('')

// 生鲜选项
const freshOptions = ref([])

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  freshFoodId: null,
  freshFoodName: '',
  originalPrice: 0,
  price: 0,
  startTime: null,
  endTime: null,
  status: '1',
  createTime: null,
  createBy: '',
  updateTime: null,
  updateBy: ''
})

// 表单校验规则
const rules = {
  freshFoodId: [
    { required: true, message: '请选择生鲜', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入促销价', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value >= formData.originalPrice) {
          callback(new Error('促销价必须低于原价'))
        } else if (value < 0) {
          callback(new Error('促销价不能小于0'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择开始时间'))
          return
        }
        const now = new Date()
        const startDate = new Date(value)
        if (startDate < now) {
          callback(new Error('开始时间不能早于当前时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择结束时间'))
          return
        }
        if (!formData.startTime) {
          callback(new Error('请先选择开始时间'))
          return
        }
        const startDate = new Date(formData.startTime)
        const endDate = new Date(value)
        if (endDate <= startDate) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await post('/sell/promotion/page', {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchText.value
    })
    if (res && res.data) {
      tableData.value = res.data.records.map(item => ({
        ...item,
        startTime: item.startTime,  // 确保时间字段正确映射
        endTime: item.endTime,
        status: item.status?.toString() // 确保状态为字符串类型
      }))
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取生鲜列表
const fetchFreshOptions = async () => {
  try {
    // 获取所有生鲜
    const res = await get('/storage/freshFood/page', {
      pageNum: 1,
      pageSize: 1000,
      name: ''
    })
    if (res && res.data && res.data.records) {
      // 获取所有促销信息
      const promotionRes = await post('/sell/promotion/page', {
        pageNum: 1,
        pageSize: 1000
      })
      
      if (promotionRes && promotionRes.data && promotionRes.data.records) {
        // 获取已有促销的生鲜ID列表
        const promotedIds = promotionRes.data.records
          .filter(item => item.status === '1')  // 只过滤状态为启用的促销
          .map(item => item.freshFoodId)
        
        // 过滤掉已有促销的生鲜（仅在新增时过滤）
        if (dialogType.value === 'add') {
          freshOptions.value = res.data.records.filter(item => !promotedIds.includes(item.id))
        } else {
          // 编辑时，除了当前编辑的商品，其他有促销的商品都不能选
          freshOptions.value = res.data.records.filter(item => 
            !promotedIds.includes(item.id) || item.id === formData.freshFoodId
          )
        }
      } else {
        // 如果没有促销信息，直接使用所有生鲜
        freshOptions.value = res.data.records
      }
    }
  } catch (error) {
    console.error('获取生鲜列表失败:', error)
    ElMessage.error('获取生鲜列表失败')
  }
}

// 生鲜选择改变时的处理
const handleFreshChange = (value) => {
  const selectedFresh = freshOptions.value.find(item => item.id === value)
  if (selectedFresh) {
    formData.freshFoodName = selectedFresh.name
    formData.originalPrice = selectedFresh.price
    formData.price = 0  // 重置促销价
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
  fetchFreshOptions()  // 在打开对话框时获取生鲜列表
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  fetchFreshOptions()
  
  // 深拷贝数据，确保时间字段正确
  Object.assign(formData, {
    ...row,
    freshFoodId: row.freshFoodId,
    freshFoodName: row.freshFoodName,
    originalPrice: parseFloat(row.originalPrice),
    price: parseFloat(row.price),
    startTime: row.startTime,  // 确保开始时间正确赋值
    endTime: row.endTime,      // 确保结束时间正确赋值
    status: row.status?.toString()
  })
}

// 删除
const handleDelete = async (id) => {
  try {
    const res = await post('/sell/promotion/remove', { id })
    if (res && res.code === 200) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      fetchData()
    } else {
      ElMessage.error(res?.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构造提交数据，确保时间格式正确
        const submitData = {
          ...formData,
          freshFoodId: parseInt(formData.freshFoodId),
          originalPrice: parseFloat(formData.originalPrice),
          price: parseFloat(formData.price),
          startTime: formData.startTime,  // 确保开始时间正确传递
          endTime: formData.endTime,      // 确保结束时间正确传递
          status: formData.status?.toString()
        }

        const url = dialogType.value === 'add' ? '/sell/promotion/save' : '/sell/promotion/update'
        const res = await post(url, submitData)
        
        if (res && res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          await fetchData()
        } else {
          ElMessage.error(res?.msg || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    freshFoodId: null,
    freshFoodName: '',
    originalPrice: 0,
    price: 0,
    startTime: null,
    endTime: null,
    status: '1',
    createTime: null,
    createBy: '',
    updateTime: null,
    updateBy: ''
  })
}

// 添加日期处理函数
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 开始时间禁用规则
const disabledStartDate = (time) => {
  const now = new Date()
  now.setHours(0, 0, 0, 0)
  return time.getTime() < now.getTime()
}

// 结束时间禁用规则
const disabledEndDate = (time) => {
  if (!formData.startTime) {
    return false
  }
  const startDate = new Date(formData.startTime)
  return time.getTime() <= startDate.getTime()
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.promotion-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>